<template>
  <span>
    <el-upload
      :before-remove="beforeRemove"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handelError"
      :file-list="fileList"
      list-type="picture-card"
      v-bind="fld"
      :action="fld.action"
      size="mini"
      ref="elupload"
      >
      <el-button type="primary">{{fld.title}}</el-button>

    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </span>
</template>
<script>
define(['vue'],function(vue){
  return vue.component('comp-image',{
    template: template,
    props:['fld','value'],
    data:function(){
      return {
        // fileList: this.value==''?[]:this.value,
        // fileList: [
        //   {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'},
        //   {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}
        // ],
        dialogImageUrl: '',
        dialogVisible: false,
        action:this.fld.action,
        actionRemove : this.fld.actionRemove,
        fileList : [],
      };
    },
    watch : {
      //监听value的变化，在主从表单中可能存在value的变化，需要联动改变filelist
      //但是$emit会抛出变化，导致这个重复触发，产生闪烁bug.
      'value':  {
        deep: true,
        immediate:true,
        handler : function(newVal,oldVal) {
          // dump(this);
          // dump(newVal,oldVal);
          if(!newVal) {
            this.fileList = [];
            return;
          }
          //比较newVal中的图片的url和this.$refs.elupload.uploadFiles中的url是否相同，
          //如果相同，说明是用户点击上传的，所以不需要改变fileList
          var oFiles = this.$refs.elupload?this.$refs.elupload.uploadFiles:[];
          if(oFiles.length!=newVal.length) {
            this.fileList = newVal;
            return;
          }
          for(var i=0;newVal[i];i++) {
            if(oFiles[i].url!=newVal[i].url) {
              this.fileList = newVal;
              return;
            }
            //相等，则继续
          }
          //全部相等，则不需要改变
        }
      }
    },
    computed:{
      // fileList : function(){
      //   if(!this.value) return [];
      //   return this.value;
      // }
    },
    methods:{
      // handleModelInput :function(val){
      //   this.$emit("input", val);
      // },
      setFileList : function(fl) {
        this.fileList = fl==''?[]:fl;
      },
      'beforeRemove' : function(file, fileList){
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      //点击文件列表项时触发
      'handlePreview' : function(file){
        // debugger;
        // this.$root.row.pic[0].url='aaa';
        // dump(111);return;
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      'handelError': function(err, file, fileList) {
        var objErr = JSON.parse(err.toString().substr(7));
        var msg = objErr.msg || '图片保存失败';
        this.$notify.warning({
            'title':'上传失败',
            'message':msg || 'response.data.success not found'
        });
        // dump(objErr.msg);
        return false;
      },
      'handleRemove' : function(file, fileList){
        //从服务器删除图片
        if(this.actionRemove) {
          var param = {url:file.url};
          this.$http.post(this.actionRemove,param).then((res)=>{
            if(!res.data.success) {
              this.$notify.error({
                'title':'服务器删除图片失败',
                'message':'response.data.success not found'
              });
              dump(res);
              return false;
            }
            this.$emit('input',fileList);
            this.$emit('changeimg',fileList,this);
            this.$notify.success({
              title:'图片删除成功',
              message:res.data.msg,
            });
            //删除回调
            var key = `${this.fld.name}:remove`;
            if(!this.$root.callbacks[key]) return;
            this.$root.callbacks[key].apply(this,arguments);
          }).catch(function (error) {
            dump(error);
            this.$notify.error({
              'title':'请求失败',
              'message':'请求失败,检查url或者其他设置'
            });
          });
        } else {
          //如果没有设置服务器删除代码,直接删除回调
          var key = `${this.fld.name}:remove`;
          if(!this.$root.callbacks[key]) return;
          this.$root.callbacks[key].apply(this,arguments);
        }

      },
      'handleExceed' : function(files, fileList){
        this.$message(`当前限制选择${this.fld.limit}个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      // 'beforeUpload': function(file) {
      //   dump('beforeUpload fired');
      // },
      'handleSuccess':function(response, file, fileList) {
        if(!response.success) {
          this.$notify.warning('图片保存存在问题,您需要重新上传!');
          return false;
        }

        if(!response.imgPath) {
          this.$notify.warning('图片保存后未返回imgPath!');
          return false;
        }
        file.url=response.imgPath;
        //格式化fileList,去掉不需要的字段信息
        var fl = [];
        fileList.forEach((item,i)=>{
          fl.push({name:item.name,url:item.url,imageId:item.imageId||item.response.imageId});
        });
        // this.fileList = fl;
        this.$emit('input',fl);
        this.$emit('changeimg',fileList,this);

        //文件上传成功后回调
        var key = `${this.fld.name}:success`;
        if(!this.$root.callbacks[key]) return;
        this.$root.callbacks[key].apply(this,arguments);
      }
    },
    mounted: function(){
      if(this.fld.action=='') {
        console.warn(`文件上传控件${this.fld.name}未定义action`);
        return ;
      }
      // dump('file mounted:this:',this);
    }
  });
});

</script>